/*
============================================================================
 Name		: CFindMe2ndAppUi.cpp
 Author	  : Ignacio Lopez
 Copyright   : GPL
 Description : CFindMe2ndAppUi implementation
============================================================================
*/

// INCLUDE FILES
#include "FindMe2ndApp.h"
#include "FindMe2ndAppui.h"
#include <FindMe2nd.rsg>
#include "FindMe2nd.hrh"
#include "FindMe2nd.hlp.hrh"

#include <avkon.hrh>
#include <aknnotewrappers.h>
#include <aknmessagequerydialog.h>
#include <hlplch.h>

#include <aknlists.h>
#include <cdblen.h>
#include <commdb.h>

#include "CBTEngine.h"
#include "CControlConnection.h"

/* Not sure I need the next ones */
#include <avkon.hrh>
#include <aknmessagequerydialog.h>
#include <aknglobalnote.h>
#include <hlplch.h>
/*end not sure */

class TEApList
{
	public:
	TUint32 iId;
	TBuf<KCommsDbSvrMaxFieldLength> iName;
};

// ================= MEMBER FUNCTIONS =======================
//
// ----------------------------------------------------------
// CFindMe2ndAppUi::ConstructL()
//
// ----------------------------------------------------------
//
void CFindMe2ndAppUi::ConstructL()
	{
	BaseConstructL();

	/*iAppContainer = new (ELeave) CFindMe2ndContainer;
	iAppContainer->SetMopParent( this );
	iAppContainer->ConstructL( ClientRect() );
	AddToStackL( iAppContainer );
	*/
	
	CEikStatusPane* sp = StatusPane();

	// Fetch pointer to the default navi pane control
	iNaviPane = (CAknNavigationControlContainer*)sp->ControlL( 
		TUid::Uid(EEikStatusPaneUidNavi));

	// Tabgroup has been read from resource and it were pushed to the navi pane. 
	// Get pointer to the navigation decorator with the ResourceDecorator() function. 
	// Application owns the decorator and it has responsibility to delete the object.
	iDecoratedTabGroup = iNaviPane->ResourceDecorator();
	if (iDecoratedTabGroup)
		{
		iTabGroup = (CAknTabGroup*) iDecoratedTabGroup->DecoratedControl();
		iTabGroup->SetObserver( this );
		}

	view1 = new (ELeave) CFindMe2ndViewStatus;

	CleanupStack::PushL( view1 );
	view1->ConstructL();
	AddViewL( view1 );	  // transfer ownership to CAknViewAppUi
	CleanupStack::Pop();	// view1

	view2 = new (ELeave) CFindMe2ndViewGps;

	CleanupStack::PushL( view2 );
	view2->ConstructL();
	AddViewL( view2 );	  // transfer ownership to CAknViewAppUi
	CleanupStack::Pop();	// view2

	SetDefaultViewL(*view1);
	
	iAnswer = CAnswer::NewL(*this); 
	
	}

// ----------------------------------------------------
// CFindMe2ndAppUi::~CFindMe2ndAppUi()
// Destructor
// Frees reserved resources
// ----------------------------------------------------
//
CFindMe2ndAppUi::~CFindMe2ndAppUi()
	{
	/*
	if (iAppContainer)
		{
		RemoveFromStack( iAppContainer );
		delete iAppContainer;
		}*/
	if (iAnswer) {
		delete iAnswer;
		iAnswer = NULL;
	}
	/* 					I thinks is done by CAknViewAppUi!!
	if (view2) {
		delete view1;
		view1=NULL;
	}
	
	if (view1) {
		delete view2;
		view2=NULL;
	} */ 
	
	delete iDecoratedTabGroup;
	}
// ------------------------------------------------------------------------------
// CFindMe2ndAppUi::DynInitMenuPaneL(TInt aResourceId,CEikMenuPane* aMenuPane)
//  This function is called by the EIKON framework just before it displays
//  a menu pane. Its default implementation is empty, and by overriding it,
//  the application can set the state of menu items dynamically according
//  to the state of application data.
// ------------------------------------------------------------------------------
//
void CFindMe2ndAppUi::DynInitMenuPaneL(
	TInt /*aResourceId*/,CEikMenuPane* /*aMenuPane*/)
	{
	}

// ----------------------------------------------------
// CFindMe2ndAppUi::HandleKeyEventL(
//	 const TKeyEvent& aKeyEvent,TEventCode /*aType*/)
// takes care of key event handling
// ----------------------------------------------------
//
TKeyResponse CFindMe2ndAppUi::HandleKeyEventL(
		const TKeyEvent& aKeyEvent,TEventCode aType)
	{
	if ( iTabGroup == NULL )
		{
		return EKeyWasNotConsumed;
		}

	if ( aKeyEvent.iCode == EKeyLeftArrow || aKeyEvent.iCode == EKeyRightArrow )
		{
		return iTabGroup->OfferKeyEventL( aKeyEvent, aType );
		}
	else
		{
		return EKeyWasNotConsumed;
		}
	}

// ----------------------------------------------------
// CFindMe2ndAppUi::HandleCommandL(TInt aCommand)
// takes care of command handling
// ----------------------------------------------------
//
void CFindMe2ndAppUi::HandleCommandL(TInt aCommand)
	{
	switch ( aCommand )
		{
		case EAknSoftkeyExit:
		case EEikCmdExit:
			{
			Exit();
			break;
			}
		case EFindMe2ndCmdAppTest:
			{
			// Load localized message from the resource file
			HBufC* message = CEikonEnv::Static()->AllocReadResourceLC(R_MESSAGE_TEXT);
			// Show information note dialog
			CAknInformationNote* note = new (ELeave) CAknInformationNote;
			note->ExecuteLD(message->Des());
			CleanupStack::PopAndDestroy(message);
			break;
			}
		case EFindMe2ndCmdHelp:
			{
			CArrayFix<TCoeHelpContext>* buf = CCoeAppUi::AppHelpContextL();
			HlpLauncher::LaunchHelpApplicationL(iEikonEnv->WsSession(), buf);
			break;
			}
		case EFindMe2ndCmdAbout:
			{
			CAknMessageQueryDialog* dlg = new (ELeave)CAknMessageQueryDialog(); 
			dlg->PrepareLC(R_ABOUT_QUERY_DIALOG);
			HBufC* title = iEikonEnv->AllocReadResourceLC(R_ABOUT_DIALOG_TITLE);
			dlg->QueryHeading()->SetTextL(*title);
			CleanupStack::PopAndDestroy(); //title
			HBufC* msg = iEikonEnv->AllocReadResourceLC(R_ABOUT_DIALOG_TEXT);
			dlg->SetMessageTextL(*msg);
			CleanupStack::PopAndDestroy(); //msg
			dlg->RunLD(); 
			break;
			}
		case EStartConnection:
			{
			iAnswer->StartManually();
			TRAPD(err5, iAnswer->getControlConnection()->getBtEngine()->ConnectL());
			break;
			}
		case EStopConnection:
			{
			iAnswer->StopManually();
			TRAPD(err5, iAnswer->getControlConnection()->getBtEngine()->Disconnect());
			break;
		}
		case EGpsConnect:
			{
			TRAPD(err5, iAnswer->getControlConnection()->getBtEngine()->ConnectL());
			break;
		}
		case EGpsDisconnect:
			{
			TRAPD(err5, iAnswer->getControlConnection()->getBtEngine()->Disconnect());
			break;
		}
			
		case ESettingInternet:
			{
			TBuf<GPRSNAMELENGTH> nameAp;
			TInt idAp = 0;
			selectAccessPoint2L(nameAp,idAp);
			if (idAp > 0) {
				TRAPD(err3, iAnswer->getConfig()->set_GprsIAPL(idAp));
				TRAPD(err4, iAnswer->getConfig()->set_GprsNameL(nameAp));
				if (err3 != KErrNone) {
					CAknConfirmationNote* note = new (ELeave) CAknConfirmationNote();
					note->ExecuteLD(_L("Internet AP was not saved."));
				}
				else {
					CAknConfirmationNote* note = new (ELeave) CAknConfirmationNote();
					note->ExecuteLD(_L("Internet AP saved."));
					DisplayStatus(EGprs, nameAp);
				}
			}
			break;
		}
		case ESettingPhoneNumber:
		{
			TBuf<PHONENUMBERLENGTH> phoneNumber;
			TRAPD(err, iAnswer->getConfig()->get_phone_numberL(phoneNumber));
			CAknTextQueryDialog* dialog = CAknTextQueryDialog::NewL(phoneNumber, CAknQueryDialog::ENoTone);
			dialog->PrepareLC(R_QUERY_PHONE_NUMBER);
			dialog->SetMaxLength(PHONENUMBERLENGTH);
			dialog->SetPromptL(_L("Phone number:"));
			if (dialog->RunLD()) {
				TRAPD(err2, iAnswer->getConfig()->set_phone_numberL(phoneNumber));
				if (err != KErrNone) {
					CAknErrorNote* note = new (ELeave) CAknErrorNote();
					note->ExecuteLD(_L("Phone number was not saved."));
				}
				else {
					CAknConfirmationNote* note = new (ELeave) CAknConfirmationNote();
					note->ExecuteLD(_L("Phone number saved."));
				}
			}
			break;
		}
		case ESettingServer:
		{
			TBuf<SERVERNAMELENGTH> serverName;
			TRAPD(err, iAnswer->getConfig()->get_serverL(serverName));
			CAknTextQueryDialog* dialog = CAknTextQueryDialog::NewL(serverName, CAknQueryDialog::ENoTone);
			dialog->PrepareLC(R_QUERY_SERVERNAME);
			dialog->SetMaxLength(SERVERNAMELENGTH);
			dialog->SetPromptL(_L("Server:"));
			if (dialog->RunLD()) {
				TRAPD(err2, iAnswer->getConfig()->set_serverL(serverName));
				if (err != KErrNone) {
					CAknErrorNote* note = new (ELeave) CAknErrorNote();
					note->ExecuteLD(_L("Server was not saved."));
				}
				else {
					CAknConfirmationNote* note = new (ELeave) CAknConfirmationNote();
					note->ExecuteLD(_L("Server saved."));
					/* Update screen and object */
					iAnswer->getControlConnection()->setDataConnectionParameters(&serverName, 0, 0, 0);
				}
			}
			break;
		}
		case ESettingDataPort:
		{
			TUint dataPort = 2323;
			TRAPD(err, iAnswer->getConfig()->get_data_portL(dataPort));
			TInt dport = dataPort;
			CAknNumberQueryDialog* dialog = CAknNumberQueryDialog::NewL(dport, CAknQueryDialog::ENoTone);
			dialog->PrepareLC(R_QUERY_DATAPORT);
			dialog->SetPromptL(_L("Data port:"));
			if (dialog->RunLD()) {
				dataPort = dport;
				TRAPD(err2, iAnswer->getConfig()->set_data_portL(dataPort));
				if (err != KErrNone) {
					CAknErrorNote* note = new (ELeave) CAknErrorNote();
					note->ExecuteLD(_L("Data port was not saved."));
				}
				else {
					CAknConfirmationNote* note = new (ELeave) CAknConfirmationNote();
					note->ExecuteLD(_L("Data port saved."));
					iAnswer->getControlConnection()->setDataConnectionParameters(NULL, 0, dataPort, 0);
				}
			}
			break;
		}
		case ESettingDataInterval:
		{
			TUint dataInterval = 60;
			TRAPD(err, iAnswer->getConfig()->get_intervalL(dataInterval));
			TInt dinterval = dataInterval;
			CAknNumberQueryDialog* dialog = CAknNumberQueryDialog::NewL(dinterval, CAknQueryDialog::ENoTone);
			dialog->PrepareLC(R_QUERY_DATAINTERVAL);
			dialog->SetPromptL(_L("Interval (secs):"));
			if (dialog->RunLD()) {
				dataInterval = dinterval;
				TRAPD(err2, iAnswer->getConfig()->set_intervalL(dataInterval));
				if (err != KErrNone) {
					CAknErrorNote* note = new (ELeave) CAknErrorNote();
					note->ExecuteLD(_L("Interval was not saved."));
				}
				else {
					CAknConfirmationNote* note = new (ELeave) CAknConfirmationNote();
					note->ExecuteLD(_L("Interval saved."));
					iAnswer->getControlConnection()->setDataConnectionParameters(NULL, 0, 0, dataInterval);
				}
			}
			break;
		}
		case ESettingGps:
		{
			TBTDeviceResponseParamsPckg gps;
			CBTEngine::SelectBtDeviceL(gps);
			TRAPD(err, iAnswer->getConfig()->set_gps_addressL(gps().BDAddr()));
			TRAPD(err2, iAnswer->getConfig()->set_gps_nameL(gps().DeviceName()));
			if (err != KErrNone || err2 != KErrNone) {
				CAknErrorNote* note = new (ELeave) CAknErrorNote();
				note->ExecuteLD(_L("Gps not selected."));
			}
			else {
				CAknConfirmationNote* note = new (ELeave) CAknConfirmationNote();
				note->ExecuteLD(_L("Gps selected."));
				DisplayStatus(EGps, gps().DeviceName());
				iAnswer->getControlConnection()->setGpsParameters(gps().BDAddr(),1);
			}
			break;
		}
		case ESettingDeviceId:
		{
			TUint deviceId = 0;
			TRAPD(err, iAnswer->getConfig()->get_nodeIdL(deviceId));
			TInt ideviceId = deviceId;
			CAknNumberQueryDialog* dialog = CAknNumberQueryDialog::NewL(ideviceId, CAknQueryDialog::ENoTone);
			dialog->PrepareLC(R_QUERY_DEVICEID);
			dialog->SetPromptL(_L("Device Id :"));
			if (dialog->RunLD()) {
				deviceId = ideviceId;
				TRAPD(err2, iAnswer->getConfig()->set_nodeIdL(deviceId));
				if (err != KErrNone) {
					CAknErrorNote* note = new (ELeave) CAknErrorNote();
					note->ExecuteLD(_L("Device Id was not saves"));
				}
				else {
					CAknConfirmationNote* note = new (ELeave) CAknConfirmationNote();
					note->ExecuteLD(_L("Device Id saved."));
					iAnswer->getControlConnection()->setDataConnectionParameters(NULL, deviceId, 0, 0);
				}
			}
			break;
		}

		default:
			break;
		}
	}

CArrayFix<TCoeHelpContext>* CFindMe2ndAppUi::HelpContextL() const
	{
	CArrayFixFlat<TCoeHelpContext>* array = new(ELeave)CArrayFixFlat<TCoeHelpContext>(1);
	CleanupStack::PushL(array);
	array->AppendL(TCoeHelpContext(KUidFindMe2nd, KGeneral_Information));
	CleanupStack::Pop(array);
	return array;
	}

void CFindMe2ndAppUi::TabChangedL(TInt aIndex)
	{
	ActivateLocalViewL(TUid::Uid(iTabGroup->TabIdFromIndex(aIndex)));
	}


void CFindMe2ndAppUi::selectAccessPoint2L(TDes& aApName, TInt& aApId)
	{
		    CArrayFixFlat<TEApList>* iEApList=new (ELeave) CArrayFixFlat<TEApList>(2) ;
			TInt stack=0;
		    // Make listitems. and PUSH it
		    CAknSinglePopupMenuStyleListBox* list = new(ELeave) CAknSinglePopupMenuStyleListBox;
		    CleanupStack::PushL(list);stack++; 
		 
		    // Create popup list and PUSH it.
		    CAknPopupList* popupList = CAknPopupList::NewL(list,
		        R_AVKON_SOFTKEYS_OK_CANCEL, AknPopupLayouts::EMenuWindow);
		    CleanupStack::PushL(popupList);stack++; 
		 
		    CDesCArrayFlat* items = new (ELeave) CDesCArrayFlat(5); /* requires library : bafl.lib */
		    CleanupStack::PushL(items);stack++; 
		    // initialize listbox.
		    list->ConstructL(popupList, CEikListBox::ELeftDownInViewRect);
		    list->CreateScrollBarFrameL(ETrue);
		    list->ScrollBarFrame()->SetScrollBarVisibilityL(CEikScrollBarFrame::EOff,
		        CEikScrollBarFrame::EAuto);
		 
		 
		    TBuf<52> iapfromtable;
		    TInt err = KErrNone;
		 
		    CCommsDatabase* iCommsDB=CCommsDatabase::NewL(EDatabaseTypeIAP);
		    CleanupStack::PushL(iCommsDB);stack++; 
		#ifdef __SERIES60_3X__
		    CCommsDbTableView* gprsTable = iCommsDB->OpenIAPTableViewMatchingBearerSetLC(
		        ECommDbBearerGPRS|ECommDbBearerWLAN|ECommDbBearerVirtual,
		        ECommDbConnectionDirectionOutgoing); 
		#else
		    /* info: file cdbcols.h and http://www.symbian.com/developer/techlib/v70sdocs/doc_source/reference/cpp/CommDb/TCommDbBearerEnum.html#%3a%3aTCommDbBearer */
		    CCommsDbTableView* gprsTable = iCommsDB->OpenIAPTableViewMatchingBearerSetLC(
		    	//ECommDbBearerCSD|ECommDbBearerLAN|ECommDbBearerGPRS|ECommDbBearerVirtual, 
		    		ECommDbBearerCSD|ECommDbBearerLAN|ECommDbBearerGPRS|ECommDbBearerVirtual, 
		        ECommDbConnectionDirectionOutgoing); 
		#endif
		    User::LeaveIfError(gprsTable->GotoFirstRecord());
		    TInt i=0;
		    TUint32 id;
		    TEApList eap;	
		 
		   // TInt cur =0; //current value
		    do
		    {
		        gprsTable->ReadTextL(TPtrC(COMMDB_NAME), iapfromtable);
		        gprsTable->ReadUintL(TPtrC(COMMDB_ID), id);
		        // gprsTable->ReadUintL(TPtrC(IAP_SERVICE), id);
		        items->AppendL(iapfromtable);
		        eap.iId=id;
		        eap.iName.Copy(iapfromtable);
		        iEApList->AppendL(eap);
		 
		        err = gprsTable->GotoNextRecord();
		        i++;
		    }
		    while (err == KErrNone);
		    CleanupStack::PopAndDestroy(2); stack--; 
			
		    // Set listitems.
		    CTextListBoxModel* model = list->Model();
		    model->SetItemTextArray(items);
		    model->SetOwnershipType(ELbmOwnsItemArray);
		    CleanupStack::Pop();    
		 
		    popupList->SetTitleL(_L("IAP"));
		    list->SetListBoxObserver(popupList);
		    TInt popupOk = popupList->ExecuteLD();
		    CleanupStack::Pop();    
		    TInt iap=0;
		    if (popupOk)
		    {	
		        TInt index = list->CurrentItemIndex();
		        iap=(*iEApList)[index].iId;
		        aApId = iap;
		        aApName.Zero();
		        aApName.Copy((*iEApList)[index].iName);
		    }
		    CleanupStack::PopAndDestroy();  
		    iEApList->Reset();
		    delete iEApList;
	}

void CFindMe2ndAppUi::DisplayStatus(const enum TDisplaySection& aSection, const TDesC& aText)
	{
		view1->DisplayOnContainer(aSection,aText);
		view2->DisplayOnContainer(aSection,aText);
	}

void CFindMe2ndAppUi::ShowInformationNote(const TDesC& aText)
{
	CAknInformationNote* note = new (ELeave) CAknInformationNote;
	note->ExecuteLD(aText);
}